from copy import deepcopy

from app.settings import BASE_DIR
from utils import write_file, read_from_file, clean_path

etcd_service_module = read_from_file("{}/deploy/module/etcd/etcd.service".format(BASE_DIR))
etcd_config_module = read_from_file("{}/deploy/module/etcd/etcd.conf.yaml".format(BASE_DIR))

ETCD_CONFIG_NAME = "etcd.conf.yaml"
ETCD_SERVICE_NAME = "etcd.service"
ETCD_CA_NAME = "etcd-ca.pem"
ETCD_SERVER_CERT_NAME = "etcd-server-cert.pem"
ETCD_SERVER_KEY_NAME = "etcd-server-key.pem"
ETCD_CLIENT_CERT_NAME = "etcd-client-cert.pem"
ETCD_CLIENT_KEY_NAME = "etcd-client-key.pem"


def gen_etcd_service(out_dir, conf_dir):
    etcd_service = deepcopy(etcd_service_module)

    etcd_service = etcd_service.format(
        config_file=clean_path(conf_dir + ETCD_CONFIG_NAME),
    )

    path = clean_path(out_dir + ETCD_SERVICE_NAME)
    write_file(path, etcd_service)
    return path


def gen_etcd_cluster_config(etcd_cluster, work_dir, cert_dir):
    result = {}
    for etcd in etcd_cluster:
        etcd_config = deepcopy(etcd_config_module)
        etcd_config = etcd_config.format(
            node_name=etcd["name"],
            node_ip=etcd["ip"],
            data_dir=work_dir,
            cluster=",".join(["{}=https://{}:2380".format(e["name"], e["ip"]) for e in etcd_cluster]),
            etcd_ca=clean_path(cert_dir + ETCD_CA_NAME),
            etcd_server_cert=clean_path(cert_dir + ETCD_SERVER_CERT_NAME),
            etcd_server_key=clean_path(cert_dir + ETCD_SERVER_KEY_NAME),
            etcd_client_cert=clean_path(cert_dir + ETCD_CLIENT_CERT_NAME),
            etcd_client_key=clean_path(cert_dir + ETCD_CLIENT_KEY_NAME)

        )
        path = clean_path(etcd["dir"] + ETCD_CONFIG_NAME)
        write_file(path, etcd_config)
        result[etcd["ip"]] = path

    return result
